package com.atguigu.guli.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.serviceedu.entity.ExcelSubjectData;
import com.atguigu.guli.serviceedu.entity.Subject;
import com.atguigu.guli.serviceedu.service.SubjectService;
import com.atguigu.servicebase.exception.ServiceException;
import com.atguigu.servicebase.result.ResponseEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectService subjectService;

    //因为SubjectExcelListener不交给spring进行管理，需要自己new，不能注入其他对象
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (excelSubjectData == null) {
            throw new ServiceException(ResponseEnum.FILE_PARSING_ERROR);
        }

        QueryWrapper<Subject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("title", excelSubjectData.getOneSubjectName());

        Subject one = subjectService.getOne(queryWrapper, false);
        if (one == null){
            Subject subject = new Subject();
            subject.setParentId("0");
            subject.setTitle(excelSubjectData.getOneSubjectName());
            subjectService.save(subject);
            one = subject;
        }

        QueryWrapper<Subject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("title", excelSubjectData.getTwoSubjectName());
        Subject two = subjectService.getOne(queryWrapper2, false);
        if (two == null) {
            Subject subject = new Subject();
            subject.setParentId(one.getId());
            subject.setTitle(excelSubjectData.getTwoSubjectName());
            subjectService.save(subject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("impore 课程分类完成");
    }
}
